/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.server.game;

import com.core.utils.DateUtil;


import com.core.utils.Utils;
import com.server.database.*;
import com.server.main.ChangePass;
import com.server.main.ClientManager;
import com.server.main.FifthLogin;
import com.server.main.LoginGame;
import com.server.main.RegisterAccount;
import com.server.main.TelcoLogin;
import java.sql.Timestamp;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

/**
 *
 * @author daz
 */
public class GameManager {

    public static final int NUMBER_TABLES_IN_ROOM = 40;
    public static final int NUMBER_ROOM = 10;
    public static final int PHOM = 0;
    public static final int XENG = 1;
    public static final int TIEN_LEN = 2;
    public static final int BA_CAY = 3;
    public static final int CHESS = 4;
    public static final int SHOP = 5;
    public static final int CHINESE_CHESS = 6;
    public static final int POKER = 7;
    public static final int XI_DACH = 8;
    public static final int CA_RO = 9;
    private static final int ROOM_MONEY1 = 0;
    private static final int ROOM_MONEY2 = 50000;
    private static final int ROOM_MONEY3 = 500000;
    public static final String SMS_SYNTAX = "KSNAP";
    private static final int BIRTH_MONEY = 10000;
//    private ServerManager server;
    private GameRoom[] listPhomRom, listTienlenRom, listChessRoom, listChineseChessRoom,
            listPokerRoom, listXiDachRoom, listCaroRoom, listBaCayRoom, listRoom;
    private Hashtable<String, Integer> childSexHashtable = new Hashtable<String, Integer>();
    private Hashtable<String, GamePlayer> listPlayers;
    private Hashtable<String, String> listHackerNames;
    private Hashtable<String, ClientManager> listPlayerWaitActivate;
    private Vector<String> listPlayerName;
//    public String hackerName = "tuandu1ca";

    public GameManager() {
//        this.server = server;
        listPhomRom = new GameRoom[NUMBER_ROOM];
        listTienlenRom = new GameRoom[NUMBER_ROOM];
        listChessRoom = new GameRoom[NUMBER_ROOM];
        listChineseChessRoom = new GameRoom[NUMBER_ROOM];
        listPokerRoom = new GameRoom[NUMBER_ROOM];
        listXiDachRoom = new GameRoom[NUMBER_ROOM];
        listCaroRoom = new GameRoom[NUMBER_ROOM];
        listBaCayRoom = new GameRoom[NUMBER_ROOM];
        for (int i = 0; i < NUMBER_ROOM; i++) {
            int moneyBetDefault = 0;
            if (i >= 0 && i <= 4) {
                moneyBetDefault = 0;
            } else if (i >= 5 && i <= 7) {
                moneyBetDefault = 5000;
            } else if (i >= 8 && i <= 9) {
                moneyBetDefault = 20000;
            }
            listPhomRom[i] = new GameRoom(PHOM, this, moneyBetDefault);
            listBaCayRoom[i] = new GameRoom(BA_CAY, this, moneyBetDefault);
            listTienlenRom[i] = new GameRoom(TIEN_LEN, this, moneyBetDefault);
            listChessRoom[i] = new GameRoom(CHESS, this, moneyBetDefault);
        }
        listPlayers = new Hashtable<String, GamePlayer>();
        listPlayerName = new Vector<String>();
        listPlayerWaitActivate = new Hashtable<String, ClientManager>();
        listHackerNames = new Hashtable<String, String>();
    }

    public void switchGame(int gameType) {
        switch (gameType) {
            case CHESS:
                listRoom = listChessRoom;
                break;
            case CHINESE_CHESS:
                listRoom = listChineseChessRoom;
                break;
            case POKER:
                listRoom = listPokerRoom;
                break;
            case XENG:
                break;
            case XI_DACH:
                listRoom = listXiDachRoom;
                break;
            case TIEN_LEN:
                listRoom = listTienlenRom;
                break;
            case PHOM:
                listRoom = listPhomRom;
                break;
            case CA_RO:
                listRoom = listCaroRoom;
                break;
            case BA_CAY:
                listRoom = listBaCayRoom;
                break;
            case SHOP:
                break;
        }
    }

    public boolean enterRoom(ClientManager client) {
        switchGame(client.getGameType());
        listRoom[client.getRoomId()].removePlayer(client.getUserName());
        return listRoom[client.getRoomId()].addPlayer(listPlayers.get(client.getUserName()));
    }

    public void exitRoom(ClientManager client) {
        switchGame(client.getGameType());
        listRoom[client.getRoomId()].removePlayer(client.getUserId());
        client.setRoomId(-1);
    }

    public boolean enterTable(ClientManager client) {
        switchGame(client.getGameType());
        int roomId = client.getRoomId();
        int tableId = client.getTableId();
        listRoom[roomId].listTable[tableId].removeUser(client.getUserName());
        return listRoom[roomId].listTable[tableId].addUser(listPlayers.get(client.getUserName()));
    }

    public void sendTableInfo(ClientManager client) {
        String msg1 = "US";
        String msg2 = "SM";
        String msg3 = "PASS";
        String msg4 = "SE";
        switchGame(client.getGameType());
        for (int i = 0; i < GameManager.NUMBER_TABLES_IN_ROOM; i++) {
            msg1 += "|" + listRoom[client.getRoomId()].listTable[i].getMaxPlayersInMatch();
            msg2 += "|" + listRoom[client.getRoomId()].listTable[i].getBet();
            msg3 += "|" + listRoom[client.getRoomId()].listTable[i].getTablePassword();
            msg4 += "|" + listRoom[client.getRoomId()].listTable[i].getNumberUsers();
        }
//        client.sendMessage("MYMONEY|" + client.getUserMoney());
        client.sendMessage(msg1);
        client.sendMessage(msg2);
        client.sendMessage(msg3);
        client.sendMessage(msg4);
    }

    public GamePlayer getPlayer(String name) {
        return listPlayers.get(name);
    }

    public ClientManager getWaitActiveClient(String name) {
        return listPlayerWaitActivate.remove(name);
    }

    public void logInFifth(String userName, String passWord, ClientManager client) {
        userName = userName.toLowerCase();
        FifthLogin loginGame = new FifthLogin(userName, passWord, client);
        int loginResult = loginGame.response();
        if (loginResult == LoginGame.USER_GRANTED) {
            client.setUserName(userName);
            GamePlayer player = new GamePlayer(client);
            listPlayers.put(userName, player);
            listPlayerName.add(userName);
        } else if (loginResult == LoginGame.USER_NEED_ACTIVATE) {
            listPlayerWaitActivate.put(userName, client);
        }

        return;
    }

    public void logInTelco(String userName, String passWord, ClientManager client) {
        userName = userName.toLowerCase();
        TelcoLogin loginGame = new TelcoLogin(userName, passWord, client);
        int loginResult = loginGame.response();
        if (loginResult == LoginGame.USER_GRANTED) {
            client.setUserName(userName);
            GamePlayer player = new GamePlayer(client);
            listPlayers.put(userName, player);
            listPlayerName.add(userName);
        } else if (loginResult == LoginGame.USER_NEED_ACTIVATE) {
            listPlayerWaitActivate.put(userName, client);
        }
        return;
    }

    public void logIn(String userName, String passWord, ClientManager client) {
        userName = userName.toLowerCase();
        LoginGame loginGame = new LoginGame(userName, passWord, client);
        int loginResult = loginGame.response();
        if (loginResult == LoginGame.USER_GRANTED) {
            client.setUserName(userName);
            GamePlayer player = new GamePlayer(client);
            listPlayers.put(userName, player);
            listPlayerName.add(userName);
        } else if (loginResult == LoginGame.USER_NEED_ACTIVATE) {
            listPlayerWaitActivate.put(userName, client);
        }
        return;
    }

    private void enterChooseGame(ClientManager client, String[] part) {
        client.setGameType(Integer.parseInt(part[1]));
        String msg1 = null, msg2 = null, msg3 = null;
        switchGame(client.getGameType());
        switch (client.getGameType()) {
            case XENG:
                msg2 = "INFO|" + client.getUserInfo().getMoney();
                break;
            case SHOP:
                msg1 = "MO|" + client.getUserMoney();
                // ITEM|NAME|PRICE|PERCENT|TIMELIMIT
                msg2 = "ITEM";
                for (int i = 0; i < client.getItemInfo().numberItem; i++) {
                    msg2 += "|" + client.getItemInfo().getItemName(i);
                    msg2 += "|" + client.getItemInfo().getItemPrice(i);
                    msg2 += "|" + client.getItemInfo().getItemLuckPercent(i);
                    msg2 += "|" + client.getItemInfo().getItemTimeLimit(i);
                }
                // MYI|itemId|isActived|timeLeft
                msg3 = "MYI";
                int seconds = 0,
                 minutes;
//                    msg3 = "MYI|0|1|1000|2|0|0";
                client.updateInventory();
                for (int i = 0; i < client.getNumberItem(); i++) {
                    msg3 += "|" + client.getItem(i).getId();
                    msg3 += "|" + ((client.getItem(i).isActived()) ? 1 : 0);
                    if (client.getItem(i).isActived()) {
                        seconds = client.getItemInfo().getItemTimeLimit(client.getItem(i).getId()) * 3600
                                - (int) (System.currentTimeMillis()
                                - client.getItem(i).getStartingTime().getTime()) / 1000;
                    }
                    minutes = seconds / 60;
                    msg3 += "|" + minutes;
                }
                if (msg3.equals("MYI")) {
                    msg3 += "|";
                }
                break;
            default:
                msg2 = "GA";
                for (int i = 0; i < GameManager.NUMBER_ROOM; i++) {
                    msg2 += "|" + listRoom[i].getNumberOfPlayersInRoom();
                }
        }

        if (msg1 != null) {
            client.sendMessage(msg1);
        }
        if (msg2 != null) {
            client.sendMessage(msg2);
        }
        if (msg3 != null) {
            client.sendMessage(msg3);
        }
    }

    private void checkChooseRoom(ClientManager client, int roomId) {
        client.setRoomId(roomId);
        if (checkUserMoneyEnterRoom(client)) {
            boolean result = enterRoom(client);
            if (result) {
                sendTableInfo(client);
            } else {
                // Room is full
                client.sendMessage("FULL|");
                client.setRoomId(-1);
            }
        } else {
            int moneyNeeded = 0;
            if (client.getRoomId() >= 0 && client.getRoomId() <= 4) {
                moneyNeeded = ROOM_MONEY1;
            } else if (client.getRoomId() >= 5 && client.getRoomId() <= 7) {
                moneyNeeded = ROOM_MONEY2;
            } else if (client.getRoomId() >= 8 && client.getRoomId() <= 9) {
                moneyNeeded = ROOM_MONEY3;
            }
            client.sendMessage("NSE|" + moneyNeeded);
            client.setRoomId(-1);
        }
    }

    private void checkChooseTable(ClientManager client, String[] part) {
        int tableId = Integer.parseInt(part[1]);
        if (checkUserMoneyEnterTable(tableId, client)) {
            client.setTableId(tableId);
            boolean result = enterTable(client);
            if (result) {
                client.setEnterTable(result);
            } else {
                //ko vao duoc ban
                client.sendMessage("FULL|");
            }
        } else {
            client.sendMessage("NRO|");
        }
    }

    public void processMessage(String request, ClientManager client) {
        String[] part = Utils.split(request, '|');
        if (part[0].equals("LO")) {
            if (part.length > 3) {
                client.clientVersionCode = Integer.parseInt(part[3]);
            }
            if (part.length > 4) {
                client.device = part[4];
            }
            logIn(part[1], part[2], client);
            return;
        }

        if (part[0].equals("TELCO_LO")) {
            if (part.length > 3) {
                client.clientVersionCode = Integer.parseInt(part[3]);
            }
            logInTelco(part[1], part[2], client);
            return;
        }

        if (part[0].equals("FIFTH_LO")) {
            if (part.length > 3) {
                client.clientVersionCode = Integer.parseInt(part[3]);
            }
            logInFifth(part[1], part[2], client);
            return;
        }

        if (part[0].equals("GA")) {
            enterChooseGame(client, part);
            return;
        }

        if (part[0].equals("SE")) {
            checkChooseRoom(client, Integer.parseInt(part[1]));
            return;
        }

        if (part[0].equals("RO")) {
            checkChooseTable(client, part);
            return;
        }
        if (part[0].equals("SMS")) {
            if (part.length >= 3) {
                client.chargeMoneySms(part[1], part[2]);
            }
            return;
        }
        if (part[0].equals("RGA")) {
            String msg = "RGA|";
            client.sendMessage(msg);
            return;
        }
        if (part[0].equals("RSE")) {
            int number = 0;
            String msg = "GA";
            switchGame(client.getGameType());
            exitRoom(client);
            for (int i = 0; i < GameManager.NUMBER_ROOM; i++) {
                number = listRoom[i].getNumberOfPlayersInRoom();
                msg += "|" + number;
            }
            client.sendMessage(msg);
            return;
        }

        if (part[0].equals("REGISTER")) {
            //REGISTER|USER|PASS|GENDER|VERSION|COMPANYID
            RegisterAccount register = new RegisterAccount(part[1], part[2], part[3], part[4], part[5]);
            register.response(client);
            return;
        }

        if (part[0].equals("CPASS")) {
            //CPASS|USER|PASS|NEWPASS
            ChangePass changePass = new ChangePass(part[1], part[2], part[3]);
            changePass.response(client);
            return;
        }

        if (part[0].equals("USECARD")) {
            //USECARD|issuer|cardCode|cardSerial
            client.useCard(part[1], part[2], part[3]);
            return;
        }
        if (part[0].equals("NAME")) {
            //NAME|childName
            String childName;
            if (part.length > 1) {
                childName = part[1];
            } else {
                childName = "0";
            }
            nameChild(client, childName);
            return;
        }
        if (part[0].equals("UDRO")) {
            sendTableInfo(client);
            return;
        }


        if (part[0].equals("XENG")) {
            client.playLuckyCoint(request);
            return;
        }
        if (part[0].equals("INFO")) {
//            UserInfo userInfo = (part.length == 1 ? client.getUserInfo() : client.getUserInfo(part[1]));
            UserInfo userInfo = null;
            if (part.length == 1) {
                userInfo = client.getUserInfo();
                sendUserInfo(client, userInfo);
            } else {
                userInfo = client.getUserInfo(part[1]);
                sendFriendInfo(client, userInfo);
            }

            return;
        }
        if (part[0].equals("LF")) {
            sendListFriend(client);
            return;
        }

        if (part[0].equals("SS")) {
            client.setStatus(part[1]);
            return;
        }

        if (part[0].equals("UMO")) {
            String msg = "UMO|" + client.getUserMoney();
            client.sendMessage(msg);
            return;
        }

        if (part[0].equals("Q")) {
            client.stop();
            return;
        }
        if (part[0].equals("MSG")) {
            processMsg(client, part);
            return;
        }
        if (part[0].equals("LMSG")) {
            //LMSG|Usersend|message
            List<UserMessage> list = client.getMessage();
            sendListMessage(client, list);
            return;
        }
        if (part[0].equals("DMSG")) {
            deleteMessage(client, part);
            return;
        }
        if (part[0].equals("RMSG")) {
            //RMSG|id
            int msgId = Integer.parseInt(part[1]);
            client.setReadMessage(msgId);
            return;
        }
        if (part[0].equals("SPEAK")) {
            clientSpeak(client, part[1]);
            return;
        }
        if (part[0].equals("TL")) {
            sendTopLevel(client);
            return;
        }
        if (part[0].equals("TR")) {
            sendTopRich(client);
            return;
        }

        if (part[0].equals("SMSINFO")) {
            client.sendSmsInfo(client.getUserInfo().getCompanyId());
        }

        if (part[0].equals("SHT")) {
            sendShopHistory(client);
            return;
        }
        if (part[0].equals("SETMONEY")) {
            client.setMoney(Integer.parseInt(part[1]));
            return;
        }
        if (part[0].equals("CHECKSMS")) {
            //reply 1: thanh cong , 0: nhan qua tin trong 5 phut, 2: nhan qua 150 000 
            client.checkSms();
            return;
        }
        if (part[0].equals("CHECK_ACTIVATE")) {
            //reply 1: thanh cong , 0: nhan qua tin trong 5 phut, 2: nhan qua 150 000 
            client.checkActivate();
            return;
        }
        // Mua item
        if (part[0].equals("BUY")) {
            // BUY|itemId|soluong
//            if (Integer.parseInt(part[1]) == 4) {
//                client.setAvatar();
//            }
            client.shopping(request);
            sendListItem(client);
            return;
        }

        // Su dung item
        if (part[0].equals("API")) {
            // API|sttItem
            int index = Integer.parseInt(part[1]);
            client.applyItem(index);

            sendListItem(client);
            return;
        }
        if (part[0].equals("DELETEFRIEND")) {
            //delete friend
            //DELFRIEND|username|friend
            client.deleteFriend(part[1], part[2]);
            sendListFriend(client);
            return;
        }

        if (part[0].equals("MYI")) {
            client.updateInventory();
            sendListItem(client);
            return;
        }
        if (part[0].equals("HACKER")) {
            String hackerName = part[1];
            listHackerNames.put(hackerName, hackerName);
//            client.log("haker name :" + part[1]);
            return;
        }
        if (part[0].equals("PING_CHECK")) {
            client.sendMessage("PING_CHECK|");
            return;
        }
        if (part[0].equals("RSMK")) {
            client.sendResetInfo(part[1]);
            return;
        }
    }

    public String getHackerName(String name) {
        return listHackerNames.get(name);
    }

    private void processMsg(ClientManager client, String[] part) {
        //MSG|userRecei|kind|messenger
        // String receiver = part[1];
        int kind = Integer.parseInt(part[2]);
        switch (kind) {
            case UserMessage.MESSAGE_NORMAL:
                // Thu binh thuong
                sendMessage(client, part[1], Integer.parseInt(part[2]), part[3]);
                break;
            case UserMessage.MESSAGE_MARRY:
                // Thu cau hon
                if (client.hasRing()) {
                    sendMessage(client, part[1], Integer.parseInt(part[2]),
                            "Người chơi " + client.getUserName() + " gửi lời cầu hôn đến bạn. Bạn có đồng ý không ?");
                    client.removeRing();
                }
                break;
            case UserMessage.MESSAGE_ACCEPT_MARRY:
                // Thu dong y ket hon
                deleteAllMarryMessage(client);
                client.marryUser(part[1], client.getUserName());
                sendMessage(client, "Thông báo", part[1], UserMessage.MESSAGE_NORMAL,
                        "Người chơi " + client.getUserName() + " đã đồng ý kết hôn với bạn. Hai bạn đã trở thành vợ chồng!");
                sendMessage(client, "Thông báo", client.getUserName(), UserMessage.MESSAGE_NORMAL,
                        "Bạn và " + part[1] + " đã trở thành vợ chồng.");
                // Xử lý phần kết hôn
                break;
            case UserMessage.MESSAGE_REJECT_MARRY:
                // Thu tu choi ket hon
                sendMessage(client, "Thông báo", part[1], UserMessage.MESSAGE_NORMAL,
                        "Người chơi " + client.getUserName() + " đã từ chối lời cầu hôn của bạn!");
                break;
            case UserMessage.MESSAGE_BIRTH:
                // De nghi sinh con
                sendMessage(client, part[1], Integer.parseInt(part[2]),
                        "Người chơi " + client.getUserName() + " đề nghị có con với bạn. Bạn có đồng ý không ? (Mỗi người chơi sẽ mất 10.000 xu/lần sinh con, với xác xuất thành công là 10% và chỉ được gửi tối đa 5 yêu cầu sinh con/ngày. Nếu sinh con thành công mỗi người chơi sẽ được trợ cấp 5000 xu/ngày (bạn phải đăng nhập vào game để nhận tiền), trong vòng 1 tháng tính từ khi sinh con.)");
                break;
            case UserMessage.MESSAGE_ACCEPT_BIRTH:
                // Dong y sinh con
                deleteAllBirthMessage(client);
                birth(client);
                break;
            case UserMessage.MESSAGE_REJECT_BIRTH:
                // Khong dong y sinh con
                sendMessage(client, "Thông báo", part[1], UserMessage.MESSAGE_NORMAL,
                        "Người chơi " + client.getUserName() + " không đồng ý có con với bạn.");
                break;
            case UserMessage.MESSAGE_FRIEND:
                //kiem tra xem nick co ton tai ko
                UserInfo userInfo = client.getUserInfo(part[1]);
                if (userInfo == null) {
                    client.sendMessage("RMF|0|" + part[1]);
                } else if (client.checkFriend(part[1])) {
                    client.sendMessage("RMF|2|" + part[1]);
                } else {
                    client.sendMessage("RMF|1|" + part[1]);
                    sendMessage(client, part[1], UserMessage.MESSAGE_FRIEND, "Người chơi: " + client.getUserName()
                            + " gửi lời kết bạn với bạn");
                }
                break;
            case UserMessage.MESSAGE_ACCEPT_FRIEND:
                sendMessage(client, "Thông báo", part[1], UserMessage.MESSAGE_ACCEPT_FRIEND, "Người chơi: " + client.getUserName()
                        + " đã đồng ý kết bạn với bạn");
                client.insertNewFriend(part[1]);
                break;
            case UserMessage.MESSAGE_REJECT_FRIEND:
                sendMessage(client, "Thông báo", part[1], UserMessage.MESSAGE_ACCEPT_FRIEND, "Người chơi: " + client.getUserName()
                        + " đã từ chối kết bạn với bạn");
                break;
        }
    }

    private void deleteMessage(ClientManager client, String[] part) {
        //DMSG|number|id|id|id
        int numberDelete = Integer.parseInt(part[1]);
        numberDelete = (numberDelete <= client.getMessage().size() ? numberDelete : client.getMessage().size());
        for (int i = 0; i < numberDelete; i++) {
            int messageId = Integer.parseInt(part[i + 2]);
            client.getMessage().get(messageId).setDelete();
        }
        for (int i = client.getMessage().size() - 1; i >= 0; i--) {
            if (client.getMessage().get(i).getIsDelete()) {
                client.deleteMessage(i);
                client.getMessage().remove(i);
            }
        }
    }

    private void deleteAllMarryMessage(ClientManager client) {
        DataEngine.getInstance().deleteAllMarryMessage(client.getUserName());
        for (int i = client.getMessage().size() - 1; i >= 0; i--) {
            if (client.getMessage().get(i).getKind() == UserMessage.MESSAGE_MARRY) {
                client.getMessage().remove(i);
            }
        }
        sendListMessage(client, client.getMessage());
    }

    private void deleteAllBirthMessage(ClientManager client) {
        DataEngine.getInstance().deleteAllBirthMessage(client.getUserName());
        for (int i = client.getMessage().size() - 1; i >= 0; i--) {
            if (client.getMessage().get(i).getKind() == UserMessage.MESSAGE_BIRTH) {
                client.getMessage().remove(i);
            }
        }
        sendListMessage(client, client.getMessage());
    }

    private void clientSpeak(ClientManager client, String content) {
        if (client.hasSpeaker()) {
            client.deleteSpeaker();
            String msg = "SPEAK";
            msg += "|" + client.getUserName();
            msg += "|" + content;
            sendToAllPlayerInGame(msg, client.getGameType());
        } else {
            client.sendMessage("SPEAK|0");
        }
    }

    private void sendTopLevel(ClientManager client) {
        List<UserInfo> listUserInfos = client.getTopLevel();
        StringBuilder infoBuilder = new StringBuilder();
        int numberInfos = (listUserInfos.size() < 10 ? listUserInfos.size() : 10);
        client.sendMessage("TL|1|" + numberInfos);
        //TL|name|gender|level
        for (int i = 0; i < numberInfos; i++) {
            infoBuilder.setLength(0);
            infoBuilder.append("TL");
            infoBuilder.append("|");
            infoBuilder.append(listUserInfos.get(i).getUserName());
            infoBuilder.append("|");
            infoBuilder.append(listUserInfos.get(i).getGender());
            infoBuilder.append("|");
            infoBuilder.append(listUserInfos.get(i).getLevel());
            infoBuilder.append("|");
            infoBuilder.append(listUserInfos.get(i).getAvatarId());
            client.sendMessage(infoBuilder.toString());
        }
        client.sendMessage("TL|-1");
    }

    private void sendTopRich(ClientManager client) {
        List<UserInfo> listUserInfos = client.getTopRich();
        StringBuilder infoBuilder = new StringBuilder();
        int numberInfos = (listUserInfos.size() < 10 ? listUserInfos.size() : 10);
        client.sendMessage("TR|1|" + numberInfos);
        //TL|name|gender|money
        for (int i = 0; i < numberInfos; i++) {
            infoBuilder.setLength(0);
            infoBuilder.append("TR");
            infoBuilder.append("|");
            infoBuilder.append(listUserInfos.get(i).getUserName());
            infoBuilder.append("|");
            infoBuilder.append(listUserInfos.get(i).getGender());
            infoBuilder.append("|");
            infoBuilder.append(listUserInfos.get(i).getMoney());
            infoBuilder.append("|");
            infoBuilder.append(listUserInfos.get(i).getAvatarId());
            client.sendMessage(infoBuilder.toString());
        }
        client.sendMessage("TR|-1");
    }

    private void sendShopHistory(ClientManager client) {
        //HST|time|kindAct|kindItem
        String msg = "SHT";
        List<ShopHistoryItem> list = client.getListShopHistory();
        for (int i = 0; i < list.size(); i++) {
            msg += "|" + list.get(i).time;
            msg += "|" + list.get(i).kindAct;
            msg += "|" + list.get(i).kindItem;
        }
        client.sendMessage(msg);
    }

    public void sendMessage(ClientManager client, String userReceive, int kind, String message) {
        Timestamp newTime = DateUtil.newTimestamp();
        client.sendMessageToUser(userReceive, newTime, kind, message);
        GamePlayer playerReceive = listPlayers.get(userReceive);
        if (playerReceive != null) {
            playerReceive.response("NMSG|" + client.getUserName() + "|" + kind + "|" + message);
            UserMessage newMessage = new UserMessage();
            newMessage.setUserSend(client.getUserName());
            newMessage.setKind(kind);
            newMessage.setMessage(message);
            newMessage.setTime(newTime);
            if (playerReceive.parent.isLoadMessage()) {
                playerReceive.parent.getMessage().add(newMessage);
            }
        }
    }

    public void sendMessage(ClientManager client, String userSend, String userReceive, int kind, String message) {
        Timestamp newTime = DateUtil.newTimestamp();
        client.sendMessageToUser(userSend, userReceive, newTime, kind, message);
        GamePlayer playerReceive = listPlayers.get(userReceive);
        if (playerReceive != null) {
            playerReceive.response("NMSG|" + userSend + "|" + kind + "|" + message);
            UserMessage newMessage = new UserMessage();
            newMessage.setUserSend(userSend);
            newMessage.setKind(kind);
            newMessage.setMessage(message);
            newMessage.setTime(newTime);
            if (playerReceive.parent.isLoadMessage()) {
                playerReceive.parent.getMessage().add(newMessage);
            }
        }
    }

    public void sendToAllPlayerInGame(String msg, int gameType) {
        for (int i = 0; i < listPlayerName.size(); i++) {
            GamePlayer player = listPlayers.get(listPlayerName.elementAt(i));
            if (player == null) {
                listPlayers.remove(listPlayerName.elementAt(i));
                continue;
            }
            if (player.parent.getGameType() == gameType) {
                player.sendMessage(msg);
            }
        }
    }

    private void sendUserInfo(ClientManager client, UserInfo userInfo) {
        //INFO|name|money|gender|levelwin|lose|status|levelComplete
        StringBuilder infoBuilder = new StringBuilder();
        infoBuilder.append("INFO|");
        infoBuilder.append(userInfo.getUserName());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getMoney());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getGender());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getLevel());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getNumberWin());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getNumberLose());
        infoBuilder.append("|");
        infoBuilder.append((userInfo.getStatus().equals("") ? "0" : userInfo.getStatus()));
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getAvatarId());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getLevelComplete());
        client.sendMessage(infoBuilder.toString());
        MateInfo mateInfo = client.getMateInfo();
        if (mateInfo == null) {
            client.sendMessage("FAMILY|0");
        } else {
            client.setMateInfo(mateInfo);
            List<ChildInfo> childList = client.getChildInfo();
            StringBuilder childInfoBuilder = new StringBuilder();
            int numberChild = childList.size();
            childInfoBuilder.append("FAMILY|1|");
            childInfoBuilder.append(mateInfo.getMateName1());
            childInfoBuilder.append("|");
            childInfoBuilder.append(mateInfo.getMateName2());
            childInfoBuilder.append("|");
            childInfoBuilder.append(numberChild);
            for (int i = 0; i < numberChild; i++) {
                childInfoBuilder.append("|");
                childInfoBuilder.append(childList.get(i).getChildName());
                childInfoBuilder.append("|");
                childInfoBuilder.append(childList.get(i).getChildGender());
            }
            client.sendMessage(childInfoBuilder.toString());
        }
    }

    private void sendFriendInfo(ClientManager client, UserInfo userInfo) {
        //INFO|name|money|gender|levelwin|lose|status|levelComplete
        StringBuilder infoBuilder = new StringBuilder();
        infoBuilder.append("INFO|");
        infoBuilder.append(userInfo.getUserName());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getMoney());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getGender());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getLevel());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getNumberWin());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getNumberLose());
        infoBuilder.append("|");
        infoBuilder.append((userInfo.getStatus().equals("") ? "0" : userInfo.getStatus()));
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getAvatarId());
        infoBuilder.append("|");
        infoBuilder.append(userInfo.getLevelComplete());
        client.sendMessage(infoBuilder.toString());
        MateInfo mateInfo = client.getMateInfo(userInfo.getUserName());
        if (mateInfo == null) {
            client.sendMessage("FAMILY|0");
        } else {
            List<ChildInfo> childList = client.getChildInfo(userInfo.getUserName());
            StringBuilder childInfoBuilder = new StringBuilder();
            int numberChild = childList.size();
            childInfoBuilder.append("FAMILY|1|");
            childInfoBuilder.append(mateInfo.getMateName1());
            childInfoBuilder.append("|");
            childInfoBuilder.append(mateInfo.getMateName2());
            childInfoBuilder.append("|");
            childInfoBuilder.append(numberChild);
            for (int i = 0; i < numberChild; i++) {
                childInfoBuilder.append("|");
                childInfoBuilder.append(childList.get(i).getChildName());
                childInfoBuilder.append("|");
                childInfoBuilder.append(childList.get(i).getChildGender());
            }
            client.sendMessage(childInfoBuilder.toString());
        }
    }

    private void sendListFriend(ClientManager client) {
        List<FriendInfo> friendList = client.getListFriend();
        StringBuilder friendListBuilder = new StringBuilder();
        //LF|1|number friend
        friendListBuilder.append("LF|1");
        int numberFriend = friendList.size();
        friendListBuilder.append("|");
        friendListBuilder.append(numberFriend);
        client.sendMessage(friendListBuilder.toString());
        for (int i = 0; i < numberFriend; i++) {
            //LF|name|isOnline|status|gender|ismaried|hasAvatar
            friendListBuilder.setLength(0);
            friendListBuilder.append("LF");
            friendListBuilder.append("|");
            friendListBuilder.append(friendList.get(i).getName());
            friendListBuilder.append("|");
            friendListBuilder.append(friendList.get(i).getIsOnline());
            String status = friendList.get(i).getStatus();
            status = (status.length() == 0 ? "0" : status);
            friendListBuilder.append("|");
            friendListBuilder.append(status);
            friendListBuilder.append("|");
            friendListBuilder.append(friendList.get(i).getGender());
            friendListBuilder.append("|");
            friendListBuilder.append(checkMaried(client, friendList.get(i).getName()));
            friendListBuilder.append("|");
            friendListBuilder.append(friendList.get(i).getAvatarId());
            client.sendMessage(friendListBuilder.toString());
        }
        //LF|-1
        friendListBuilder.setLength(0);
        friendListBuilder.append("LF");
        friendListBuilder.append("|");
        friendListBuilder.append(-1);
        client.sendMessage(friendListBuilder.toString());

    }

    private void sendListItem(ClientManager client) {
        String msg = "MYI";
        int seconds = 0, minutes;
        client.updateInventory();
        for (int i = 0; i < client.getNumberItem(); i++) {
            msg += "|" + client.getItem(i).getId();
            msg += "|" + ((client.getItem(i).isActived()) ? 1 : 0);
            if (client.getItem(i).isActived()) {
                seconds = client.getItemInfo().getItemTimeLimit(client.getItem(i).getId()) * 3600
                        - (int) (System.currentTimeMillis()
                        - client.getItem(i).getStartingTime().getTime()) / 1000;
            }
            minutes = seconds / 60;
            msg += "|" + minutes;
        }
        if (msg.equals("MYI")) {
            msg += "|";
        }
        client.sendMessage(msg);
    }

    private int checkMaried(ClientManager client, String name) {
        MateInfo mateInfo = client.getMateInfo(name);
        if (mateInfo == null) {
            return 0;
        }
        return 1;
    }

    private void birth(ClientManager client) {
        int random = Utils.nextInt(100);
        if (client.getUserMoney() >= BIRTH_MONEY && client.getMateMoney() >= BIRTH_MONEY) {
            client.updateMoneyDelta(-BIRTH_MONEY);
            client.updateMateMoney(-BIRTH_MONEY);
            if ((random >= 0) && (random <= 10)) {
                random = Utils.nextInt(2);
                childSexHashtable.put(client.getMateName(), random);
                switch (random) {
                    case 0:
                        sendMessage(client, "Thông báo", client.getMateName(), UserMessage.MESSAGE_ACCEPT_BIRTH,
                                "Chúc mừng, bạn vừa sinh được một bé trai xinh xắn. Hãy đặt tên cho bé nhé.");
                        break;
                    case 1:
                        sendMessage(client, "Thông báo", client.getMateName(), UserMessage.MESSAGE_ACCEPT_BIRTH,
                                "Chúc mừng, bạn vừa sinh được một bé gái xinh xắn. Hãy đặt tên cho bé nhé.");
                        break;
                }
            } else {
                sendMessage(client, "Thông báo", client.getUserName(), UserMessage.MESSAGE_NORMAL,
                        "Bạn đã sinh con thất bại. Chúc may mắn hơn lần sau.");
                sendMessage(client, "Thông báo", client.getMateName(), UserMessage.MESSAGE_NORMAL,
                        "Bạn đã sinh con thất bại. Chúc may mắn hơn lần sau.");
            }
        } else {
            sendMessage(client, "Thông báo", client.getUserName(), UserMessage.MESSAGE_NORMAL,
                    "Bạn hoặc người chơi đã kết hôn với bạn không có đủ tiền để sinh con. (Mỗi người chơi sẽ phải mất 10.000 xu/lần sinh con.)");
            sendMessage(client, "Thông báo", client.getMateName(), UserMessage.MESSAGE_NORMAL,
                    "Bạn hoặc người chơi đã kết hôn với bạn không có đủ tiền để sinh con. (Mỗi người chơi sẽ phải mất 10.000 xu/lần sinh con.)");
        }
    }

    private void nameChild(ClientManager client, String childName) {
        if (childName == null) {
            childName = "0";
        }
        int sex = childSexHashtable.get(client.getUserName());
        childSexHashtable.remove(client.getUserName());
        client.insertChild(childName, sex);
        sendMessage(client, "Thông báo", client.getMateName(), UserMessage.MESSAGE_NORMAL,
                "Chúc mừng, bạn vừa sinh được một bé " + (sex == 0 ? "trai" : "gái") + " xinh xắn tên là " + childName);
    }

    private void sendListMessage(ClientManager client, List<UserMessage> list) {
        int numberMessages = list.size();
        client.sendMessage("LMSG|1|" + numberMessages);
        if (numberMessages > 0) {
            StringBuilder messageBuilder = new StringBuilder();
            for (int i = 0; i < numberMessages; i++) {
                messageBuilder.setLength(0);
                messageBuilder.append("LMSG");
                messageBuilder.append("|");
                messageBuilder.append(list.get(i).getUserSend());
                messageBuilder.append("|");
                messageBuilder.append(list.get(i).getKind());
                messageBuilder.append("|");
                messageBuilder.append(list.get(i).getMessage());
                messageBuilder.append("|");
                messageBuilder.append(list.get(i).getIsRead());
                client.sendMessage(messageBuilder.toString());
            }
        }
        client.sendMessage("LMSG|-1");
    }

    private boolean checkUserMoneyEnterRoom(ClientManager client) {
        if (client.getRoomId() >= 0 && client.getRoomId() <= 4) {
            if (client.getUserMoney() >= ROOM_MONEY1) {
                return true;
            }
            return false;

        } else if (client.getRoomId() >= 5 && client.getRoomId() <= 7) {
            if (client.getUserMoney() >= ROOM_MONEY2) {
                return true;
            }
            return false;

        } else if (client.getRoomId() >= 8 && client.getRoomId() <= 9) {
            if (client.getUserMoney() >= ROOM_MONEY3) {
                return true;
            }
            return false;
        }
        return false;
    }

    private boolean checkUserMoneyEnterTable(int tableId, ClientManager client) {
        if (client.getUserMoney() >= 5 * listPhomRom[client.getRoomId()].listTable[tableId].getBet()) {
            return true;
        }
        return false;

    }

    public void removeFromMap(String clientName) {
        listPlayers.remove(clientName);
        listPlayerName.removeElement(clientName);
    }
}
